<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible" width="75%">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
      <el-form-item label="保险名称" prop="insureName">
        <el-input v-model="ruleForm.insureName"></el-input>
      </el-form-item>
      <el-form-item label="处理状态" prop="insureKind">
        <el-radio-group v-model="ruleForm.insureKind">
          <el-radio :label="1">系统处理保险</el-radio>
          <el-radio :label="2">客服处理保险</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="保险介绍">
        <el-input v-model="ruleForm.insureIntroduction" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="投保形式">
        <el-input v-model="ruleForm.insureModality" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="适用条款">
        <el-input v-model="ruleForm.clause" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="不承保物品">
        <el-input v-model="ruleForm.noProtectGoods" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="保障范围" prop="scopeOfProtection">
        <el-button @click="addScopeOfProtection">添加</el-button>
        <el-table :data="scopeOfProtectionList" style="width: 100%" size="mini">
          <el-table-column label="项目" width="180">
            <template slot-scope="scope">
              <el-input @blur="addScopeOfProtectionFunc(scope.row)" v-model="scope.row.safeguardName"
                placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="basicStatus" label="基本险" width="180">
            <template slot-scope="scope">
              <el-checkbox @change="addScopeOfProtectionFunc(scope.row)" v-model="scope.row.basicStatus"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="synthesisStatus" label="综合险">
            <template slot-scope="scope">
              <el-checkbox @change="addScopeOfProtectionFunc(scope.row)"
                v-model="scope.row.synthesisStatus"></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="delScopeOfProtection(scope)" size="mini" type="text"
                icon="el-icon-document-checked">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="最低费率(单位%)" prop="rate">
        <el-input v-model="ruleForm.rate"></el-input>
      </el-form-item>
      <el-form-item label="特备说明">
        <el-input v-model="ruleForm.statement" type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="免赔率" prop="excess">
        <el-button @click="addExcess">添加</el-button>
        <el-table :data="excessList" style="width: 100%" size="mini">
          <el-table-column prop="goodsType" label="货物类型" width="180">
            <template slot-scope="scope">
              <el-input @blur="addExcessFunc(scope.row)" v-model="scope.row.goodsType" placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="deductionType" label="免赔额">
            <template slot-scope="scope">
              <el-input @blur="addExcessFunc(scope.row)" v-model="scope.row.deductionType" type="textarea"
                placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="delExcessList(scope)" size="mini" type="text"
                icon="el-icon-document-checked">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="扩展保险" prop="extendInsure">
        <el-button @click="addExtendInsure">添加</el-button>
        <el-table :data="extendInsureList" style="width: 100%" size="mini">
          <el-table-column prop="extendInsureName" label="扩展保险名称" width="180">
            <template slot-scope="scope">
              <el-input @blur="addExtendInsureFunc(scope.row)" v-model="scope.row.extendInsureName"
                placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="extendInsureRate" label="扩展保险费率(单位%)" width="180">
            <template slot-scope="scope">
              <el-input @blur="addExtendInsureFunc(scope.row)" v-model="scope.row.extendInsureRate"
                placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button @click="delExtendInsureList(scope)" size="mini" type="text"
                icon="el-icon-document-checked">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="货物类型与费率" prop="goods">
        <el-button @click="addInsuranceType">添加</el-button>
        <span style="margin-left: 10px">实际费率 = 设置费率 - 优惠费率</span>
        <el-table ref="table" :data="goodsList">
          <el-table-column type="expand" style="padding: 30px">
            <template slot-scope="aaa">
              <el-table :data="aaa.row.insureRateGoodss || []" style="padding: 10px 50px">
                <el-table-column prop="goodsTypeName" label="货物名称" width="180">
                  <template slot-scope="scope">
                    <el-input
                      @blur="aaa.row.insureKindId ? addGoodsTypeFunc(scope.row, aaa.row) : addInsureKindNameFunc(aaa.row, scope.row)"
                      v-model="scope.row.goodsTypeName" placeholder="请输入内容"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="extendInsureRate" label="设置费率(单位%)" width="150">
                  <template slot-scope="scope">
                    <el-input
                      @blur="aaa.row.insureKindId ? addGoodsTypeFunc(scope.row, aaa.row) : addInsureKindNameFunc(aaa.row, scope.row)"
                      v-model="scope.row.goodsTypeRate" placeholder="请输入内容"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="extendInsureRate" label="vip优惠费率(单位%)" width="150">
                  <template>
                    <div v-for="item in vipLevelList" :key="item.vipId" style="margin: 5px 0">
                      <span>{{ item.vipLevel }}：{{ item.discountRate }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="extendInsureRate" label="vip优惠后费率(单位%)" width="150">
                  <template slot-scope="scope">
                    <div v-for="item in vipLevelList" :key="item.vipId" style="margin: 5px 0">
                      <span>{{ item.vipLevel }}：{{
    scope.row.goodsTypeRate
      ? count(scope.row.goodsTypeRate, item.discountRate)
      : "-"
  }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button size="mini" type="text" icon="el-icon-document-checked"
                      @click="delGoodsTypeFunc(scope, aaa)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column prop="insureKindName" label="保险种类">
            <template slot-scope="scope">
              <el-input @blur="addInsureKindNameFunc(scope.row)" v-model="scope.row.insureKindName"
                placeholder="请输入内容"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-plus" @click="addGoods(scope)">添加货物</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="delInsuranceType(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="最低保费（元）" prop="minInsureFee">
        <el-input style="width:200px" v-model="ruleForm.minInsureFee"></el-input> 起
      </el-form-item>
      <el-form-item label="选择模板" prop="templateCode">
        <el-select v-model="ruleForm.templateCode" placeholder="请选择模板">
          <el-option v-for="item in templateCodeList" :label="item.templateName" :value="item.templateCode" :key="item.templateCode"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cance">取 消</el-button>
      <el-button type="primary" @click="determine">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { deepClone } from "@/utils";
const Decimal = require("decimal.js");
export default {
  props: {
    getTableData: {
      type: Function,
    },
  },
  data() {
    return {
      insureInfoId: '',
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      vipLevelList: [],
      scopeOfProtectionList: [],
      excessList: [],
      extendInsureList: [],
      templateCodeList: [],
      goodsList: [
        {
          insureKindName: "基本险",
          insureRateGoodss: [
            {
              goodsTypeName: "",
              goodsTypeRate: "",
            },
          ],
        },
        {
          insureKindName: "综合险",
          insureRateGoodss: [
            {
              goodsTypeName: "",
              goodsTypeRate: "",
            },
          ],
        },
      ],
      insureTypeId: "",
      title: "添加保险",
      dialogFormVisible: false,
      ruleForm: {
        insureName: "",
        insureKind: 1,
        insureIntroduction: "",
        insureModality: "",
        insuranceForm: "",
        clause: "",
        noProtectGoods: "",
        scopeOfProtection: "",
        goods: "",
        minInsureFee: "50",
        rate: "",
        statement: "",
        excess: "",
        extendInsure: "",
        templateCode: "",
      },
      rules: {
        insureName: [
          { required: true, message: "请输入保险名称", trigger: "blur" },
        ],
        clause: [
          { required: true, message: "请输入适用条款", trigger: "blur" },
        ],
        noProtectGoods: [
          { required: true, message: "请输入不承担物品", trigger: "blur" },
        ],
        scopeOfProtection: [
          {
            validator: (rule, value, cb) =>
              this.checkScopeOfProtection(rule, value, cb),
          },
        ],
        goods: [
          {
            validator: (rule, value, cb) => this.checkGoods(rule, value, cb),
          },
        ],
        rate: [
          { required: true, message: "请输入费率", trigger: "blur" },
          { validator: (rule, value, cb) => this.checkRate(rule, value, cb) },
        ],
        minInsureFee: [
        { required: true, message: "请输入最低保费", trigger: "blur" },
        ],
        excess: [
          { validator: (rule, value, cb) => this.checkExcess(rule, value, cb) },
        ],
        templateCode: [
          { required: true, message: "请选择模板", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    addExcessFunc(row) {
      if (!row.goodsType || !row.deductionType) {
        return
      }
      const params = deepClone(row)
      if (this.insureInfoId) {
        params.insureInfoId = this.insureInfoId
      }
      const reqMethods = row.deductionId ? '$put' : '$post'
      const message = row.deductionId ? '修改成功' : '新增成功'
      this[reqMethods]("/insure/deduction", params).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$message({
            type: "success",
            message,
          });
        }
      });
    },
    delExcessList(scope) {
      this.excessList.splice(scope.$index, 1)
      this.$delete(`/insure/deduction/${scope.row.deductionId}`).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        }
      });
    },
    addScopeOfProtectionFunc(row) {
      if (!row.safeguardName) {
        return
      }
      const params = deepClone(row)
      if (this.insureInfoId) {
        params.insureInfoId = this.insureInfoId
      }
      params.basicStatus = row.basicStatus ? 1 : 0
      params.synthesisStatus = row.synthesisStatus ? 1 : 0
      const reqMethods = row.safeguardId ? '$put' : '$post'
      const message = row.safeguardId ? '修改成功' : '新增成功'
      this[reqMethods]("/insure/safeguard", params).then((res) => {
        if (res && res.code * 1 === 200) {
          if (!row.safeguardId) {
            row.safeguardId = res.data
          }
          this.$message({
            type: "success",
            message,
          });
        }
      });
    },
    delScopeOfProtection(scope) {
      this.scopeOfProtectionList.splice(scope.$index, 1)
      if (scope.row.safeguardId) {
        this.$delete(`/insure/safeguard/${scope.row.safeguardId}`).then((res) => {
          if (res && res.code * 1 === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        });
      }
    },

    getTemplateCodeList() {
      this.$get(`/insure/template/list`).then((res) => {
          if (res && res.code * 1 === 200) {
            this.templateCodeList = res.rows
          }
        });
    },

    addExtendInsureFunc(row) {
      if (!row.extendInsureName || !row.extendInsureRate) {
        return
      }
      const params = deepClone(row)
      if (this.insureInfoId) {
        params.insureInfoId = this.insureInfoId
      }
      const reqMethods = row.insureExtendId ? '$put' : '$post'
      const message = row.insureExtendId ? '修改成功' : '新增成功'
      this[reqMethods]("/insure/rateextend", params).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$message({
            type: "success",
            message,
          });
          if (!row.insureExtendId) {
            row.insureExtendId = res.data
          }

        }
      });
    },

    delExtendInsureList(scope) {
      this.extendInsureList.splice(scope.$index, 1)
      if (scope.row.insureExtendId) {
        this.$delete(`/insure/rateextend/${scope.row.insureExtendId}`).then((res) => {
          if (res && res.code * 1 === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        });
      }

    },

    addInsureKindNameFunc(row) {
      if (!row.insureKindName) {
        return
      }
      if (!row.insureRateGoodss && !row.insureRateGoodss.length) {
        return
      }
      for (const item of row.insureRateGoodss) {
        if (!item.goodsTypeName || !item.goodsTypeRate) {
          return
        }
      }
      const params = deepClone(row)
      if (this.insureInfoId) {
        params.insureInfoId = this.insureInfoId
      }
      const reqMethods = row.insureKindId ? '$put' : '$post'
      const message = row.insureKindId ? '修改成功' : '新增成功'
      this[reqMethods]("/insure/ratekind", params).then((res) => {
        if (res && res.code * 1 === 200) {
          this.$message({
            type: "success",
            message,
          });
          if (!row.insureKindId) {
            row.insureKindId = res.data
          }
        }
      });
    },

    delInsuranceType(scope) {
      this.goodsList.splice(scope.$index, 1)
      if (scope.row.insureKindId) {
        this.$delete(`/insure/ratekind/${scope.row.insureKindId}`).then((res) => {
          if (res && res.code * 1 === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        });
      }

    },

    addGoodsTypeFunc(row, aaa) {
      this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (!row.goodsTypeName || !row.goodsTypeRate) {
              return
            }
            const params = deepClone(row)
            params.insureKindId = aaa.insureKindId
            if (this.insureInfoId) {
              params.insureInfoId = this.insureInfoId
            }
            const reqMethods = row.insureGoodsId ? '$put' : '$post'
            const message = row.insureGoodsId ? '修改成功' : '新增成功'
            this[reqMethods]("/insure/rategoods", params).then((res) => {
              if (res && res.code * 1 === 200) {
                this.$message({
                  type: "success",
                  message,
                });
                if (!row.insureGoodsId) {
                  row.insureGoodsId = res.data
                }
              }
            });
          }
        })
    },

    delGoodsTypeFunc(scope, aaa) {
      this.goodsList[aaa.$index].insureRateGoodss.splice(scope.$index, 1)
      if (scope.row.insureGoodsId) {
        this.$delete(`/insure/rategoods/${scope.row.insureGoodsId}`).then((res) => {
          if (res && res.code * 1 === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          }
        });
      }

    },

    count(goodsTypeRate, discountRate) {
      const rg = /^([0-9]*[.])?[0-9]+$/;
      if (!rg.test(goodsTypeRate)) {
        return "-";
      }

      // 创建两个 Decimal 对象
      const num1 = new Decimal(goodsTypeRate);
      const num2 = new Decimal(discountRate);

      // 使用减法计算
      const result = num1.minus(num2);
      return result.toString()
    },
    handleRemove(file) {
      console.log(file);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    cance() {
      this.$refs.ruleForm.resetFields();
      this.dialogFormVisible = false;
    },
    addExtendInsure() {
      this.extendInsureList.unshift({
        extendInsureName: "",
        extendInsureRate: "",
      });
    },
    addExcess() {
      this.excessList.unshift({
        goodsType: "",
        deductionType: "",
      });
    },
    addInsuranceType() {
      this.goodsList.unshift({
        insureKindName: "",
        insureRateGoodss: [
          {
            goodsTypeName: "",
            goodsTypeRate: "",
          },
        ],
      });
    },
    addGoods(row) {
      const item = this.goodsList.find((item, ind) => ind === row.$index);
      item.insureRateGoodss.unshift({
        goodsTypeName: "",
        goodsTypeRate: "",
      });
    },
    checkGoods(rule, value, cb) {
      for (const item of this.goodsList) {
        if (!item.insureKindName) {
          cb("保险种类不能为空");
        }
        for (const i of item.insureRateGoodss) {
          if (!i.goodsTypeName) {
            cb("货物类型不能为空");
          }
          if (!i.goodsTypeRate) {
            cb("请设置货物类型费率");
          }
          const rg = /^((\.\d+)|(0(\.\d+)?))$/;
          if (!rg.test(i.goodsTypeRate)) {
            cb("请输入小于1的数字");
          }
          for (const o of this.vipLevelList) {
            if (this.count(i.goodsTypeRate, o.discountRate) < 0) {
              cb("设置的费率应大于优惠费率");
            }
          }
        }
      }
      cb();
    },
    checkRate(rule, value, cb) {
      const rg = /^((\.\d+)|(0(\.\d+)?))$/;
      if (!rg.test(value)) {
        cb("请输入小于1的数字");
      }
      cb();
    },
    checkExcess(rule, value, cb) {
      if (!this.excessList.length) {
        cb();
      }
      for (const item of this.excessList) {
        if (!item.goodsType) {
          cb("货物类型不能为空");
        }
        if (!item.deductionType) {
          cb("免赔额不能为空");
        }
      }
      cb();
    },
    checkScopeOfProtection(rule, value, cb) {
      if (!this.scopeOfProtectionList.length) {
        cb();
      }
      for (const item of this.scopeOfProtectionList) {
        if (!item.safeguardName) {
          cb("项目不能为空");
        }
      }
      cb();
    },
    addScopeOfProtection() {
      this.scopeOfProtectionList.unshift({
        safeguardName: "",
        basicStatus: true,
        synthesisStatus: true,
      });
    },
    determine() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          const reqMethods = this.insureInfoId ? '$put' : '$post'
          const message = this.insureInfoId ? '修改成功' : '新增成功'
          this[reqMethods]("/insure/insureinfo", this.getParams()).then((res) => {
            if (res && res.code * 1 === 200) {
              this.$message({
                type: "success",
                message,
              });
              this.dialogFormVisible = false;
              this.getTableData();
            }
          });
        }
      });
    },
    getParams() {
      const params = deepClone(this.ruleForm);
      params.insureConfigSafeguards = this.scopeOfProtectionList || [];
      params.insureConfigSafeguards.forEach((item) => {
        item.basicStatus = item.basicStatus ? 1 : 0;
        item.synthesisStatus = item.synthesisStatus ? 1 : 0;
      });
      params.insureConfigDeductions = this.excessList;
      params.insureRateExtends = this.extendInsureList;
      params.insureTypeId = this.insureTypeId;
      params.insureRateKinds = this.goodsList;
      if (this.insureInfoId) {
        params.insureInfoId = this.insureInfoId
      }
      return params;
    },
  },
  mounted() {
    this.getTemplateCodeList()
  }
};
</script>
